package com.dlm.controller;

import com.dlm.dao.Users;
import com.dlm.sdk.api.ApiResult;
import com.dlm.sdk.api.UserApi;
import com.dlm.sdk.msg.in.InVideoMsg;
import com.dlm.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.dlm.sdk.msg.out.OutNewsMsg;
import com.jfinal.kit.PropKit;
import com.dlm.sdk.api.ApiConfig;
import com.dlm.sdk.jfinal.MsgController;
import com.dlm.sdk.msg.in.InImageMsg;
import com.dlm.sdk.msg.in.InLinkMsg;
import com.dlm.sdk.msg.in.InLocationMsg;
import com.dlm.sdk.msg.in.InTextMsg;
import com.dlm.sdk.msg.in.InVoiceMsg;
import com.dlm.sdk.msg.in.event.InFollowEvent;
import com.dlm.sdk.msg.in.event.InLocationEvent;
import com.dlm.sdk.msg.in.event.InMenuEvent;
import com.dlm.sdk.msg.in.event.InQrCodeEvent;
import com.dlm.sdk.msg.out.OutImageMsg;
import com.dlm.sdk.msg.out.OutMusicMsg;
import com.dlm.sdk.msg.out.OutTextMsg;
import com.dlm.sdk.msg.out.OutVoiceMsg;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgController extends MsgController {
    private Logger logger = Logger.getLogger(WeixinMsgController.class);
//    private static final String helpStr = "帮助说明!<a>http://www.baidu.com</a>";

    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
     * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
     */
    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig();
        // 配置微信 API 相关常量
        ac.setToken(PropKit.get("token"));
        ac.setAppId(PropKit.get("appId"));
        ac.setAppSecret(PropKit.get("appSecret"));
        ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
        return ac;
    }

    /**
     * 实现父类抽方法，处理文本消息
     * 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin sdk的基本功能：
     * 本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
     * 其它类型的消息会在随后的方法中进行测试
     */
    protected void processInTextMsg(InTextMsg inTextMsg) {
        String msg = inTextMsg.getContent().trim();
        logger.debug(msg);
        if ("下单".equalsIgnoreCase(msg) || "价格".equalsIgnoreCase(msg)) {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("请点击此处\n<a>https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc6f57a1be5f8d68a&redirect_uri=http://meirongdaojia.com&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect</a>");
            render(outMsg);
        }
        //垃圾、妈的、靠、神经病
        else if ("垃圾".equalsIgnoreCase(msg) ||
                "靠".equalsIgnoreCase(msg) ||
                "妈的".equalsIgnoreCase(msg) ||
                "神经病".equalsIgnoreCase(msg)
                ) {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("亲亲，您是想了解神马呢? \ue108");
            render(outMsg);
        }
        //皮肤、护理、美容、养生、支付
        else if ("皮肤".equalsIgnoreCase(msg) ||
                "护理".equalsIgnoreCase(msg) ||
                "美容".equalsIgnoreCase(msg) ||
                "养生".equalsIgnoreCase(msg) ||
                "支付".equalsIgnoreCase(msg)
                ) {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("大脸猫的每一名美容师，均通过严格的身份登记与资质考核，在加入大脸猫之前，均在知名美容院工作多年，请您绝对放心。" +
                    "\n 同时大脸猫的每一单支付均由支付宝担保交易，如您对服务有任何的不满，均可拒付，您不会有任何的经济损失");
            render(outMsg);
        }
        //		安全、产品
        else if ("安全".equalsIgnoreCase(msg) ||
                "产品".equalsIgnoreCase(msg)
                ) {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("大脸猫所使用的美容和养生产品在市场上已经使用和推广10年以上，均为各美容院长期使用的产品，安全有绝对的保障，请放心使用。");
            render(outMsg);
        }
//		// 图文消息测试
//		else if ("news".equalsIgnoreCase(msg)) {
//			OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
//			outMsg.addNews("JFinal 1.8 发布，JAVA 极速 WEB+ORM 框架", "现在就加入 JFinal 极速开发世界，节省更多时间去跟女友游山玩水 ^_^", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200313981&idx=1&sn=3bc5547ba4beae12a3e8762ababc8175#rd");
//			outMsg.addNews("JFinal 1.6 发布,JAVA极速WEB+ORM框架", "JFinal 1.6 主要升级了 ActiveRecord 插件，本次升级全面支持多数源、多方言、多缓", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq0fcR8VmNCgugHXv7gVlxI6w95RBlKLdKUTjhOZIHGSWsGvjvHqnBnjIWHsicfcXmXlwOWE6sb39kA/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200121522&idx=1&sn=ee24f352e299b2859673b26ffa4a81f6#rd");
//			render(outMsg);
//		}
//		// 音乐消息测试
//		else if ("music".equalsIgnoreCase(msg)) {
//			OutMusicMsg outMsg = new OutMusicMsg(inTextMsg);
//			outMsg.setTitle("Listen To Your Heart");
//			outMsg.setDescription("建议在 WIFI 环境下流畅欣赏此音乐");
//			outMsg.setMusicUrl("http://www.jfinal.com/Listen_To_Your_Heart.mp3");
//			outMsg.setHqMusicUrl("http://www.jfinal.com/Listen_To_Your_Heart.mp3");
//			outMsg.setFuncFlag(true);
//			render(outMsg);
//		}
//		else if ("html".equalsIgnoreCase(msg)) {
//			OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
//			//outMsg.addNews("我们只看美女", "又一大波美女来袭，我们只看美女 ^_^", "https://mmbiz.qlogo.cn/mmbiz/zz3Q6WSrzq3DmIGiadDEicRIp69r1iccicwKEUOKuLhYgjibyU96ia581gCf5o3kicqz6ZLdsDyUtLib0q0hdgHtZOf4Wg/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=202080887&idx=1&sn=0649c67de565e2d863bf3b8feee24da0#rd");
//			// outMsg.addNews("秀色可餐", "JFinal Weixin 极速开发就是这么爽，有木有 ^_^", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq2GJLC60ECD7rE7n1cvKWRNFvOyib4KGdic3N5APUWf4ia3LLPxJrtyIYRx93aPNkDtib3ADvdaBXmZJg/0", "http://mp.weixin.qq.com/s?__biz=MjM5ODAwOTU3Mg==&mid=200987822&idx=1&sn=7eb2918275fb0fa7b520768854fb7b80#rd");
//			outMsg.addNews("标题","描述","http://a.hiphotos.baidu.com/image/pic/item/b8389b504fc2d5620ddd19e1e51190ef77c66ce1.jpg","http://wxt.oschina.mopaas.com/index.html");
//			render(outMsg);
//		}
//		else if ("楚亚洁".equalsIgnoreCase(msg)) {
//			OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
//			outMsg.addNews("楚亚洁我爱你!","描述","http://wxt.oschina.mopaas.com/img/1.png","http://wxt.oschina.mopaas.com/index.html");
//			render(outMsg);
//		}
        // 其它文本消息直接返回原值 + 帮助提示
        else {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("\t您好，您发送的信息大脸猫已收到，如有其他疑问，可随时联系我们，电话：13661329056");
            render(outMsg);
        }
    }

    /**
     * 实现父类抽方法，处理图片消息
     */
    protected void processInImageMsg(InImageMsg inImageMsg) {
        OutImageMsg outMsg = new OutImageMsg(inImageMsg);
        // 将刚发过来的图片再发回去
        outMsg.setMediaId(inImageMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理语音消息
     */
    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        OutVoiceMsg outMsg = new OutVoiceMsg(inVoiceMsg);
        // 将刚发过来的语音再发回去
        outMsg.setMediaId(inVoiceMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理视频消息
     */
    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        /* 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试
		OutVideoMsg outMsg = new OutVideoMsg(inVideoMsg);
		outMsg.setTitle("OutVideoMsg 发送");
		outMsg.setDescription("刚刚发来的视频再发回去");
		// 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api 有 bug，待 api bug 却除后再试
		outMsg.setMediaId(inVideoMsg.getMediaId());
		render(outMsg);
		*/
        OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
        outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inVideoMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理地址位置消息
     */
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
        outMsg.setContent("已收到地理位置消息:" +
                "\nlocation_X = " + inLocationMsg.getLocation_X() +
                "\nlocation_Y = " + inLocationMsg.getLocation_Y() +
                "\nscale = " + inLocationMsg.getScale() +
                "\nlabel = " + inLocationMsg.getLabel());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理链接消息
     * 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
     */
    protected void processInLinkMsg(InLinkMsg inLinkMsg) {
        OutNewsMsg outMsg = new OutNewsMsg(inLinkMsg);
        outMsg.addNews("链接消息已成功接收", "链接使用图文消息的方式发回给你，还可以使用文本方式发回。点击图文消息可跳转到链接地址页面，是不是很好玩 :)", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", inLinkMsg.getUrl());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
//        "亲爱的小主儿，大脸猫花花可把您给盼来啦！\n" +
//                "我是一个有点小臭美，有点小调皮，有点小粘人，有点小懒惰，但同时身怀各项绝技会做各种小表情的猫咪，名字叫花花，给小主请安了。\n" +
//                "初次见面，为了表达对小主的喜欢，再加上花花最近体重确实有点超标，花花决定忍痛从自己的猫粮月俸中节省一部分，敬献给小主，" +
//                "小主<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc6f57a1be5f8d68a&redirect_uri=http://meirongdaojia.com/sms/reg&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect\">点击链接，即可领取（优惠券）</a>，小小敬意，小主千万不要嫌弃。\n" +
//                "小主要是喜欢花花，就尽快把我带回家吧。偷偷告诉小主儿，上门时还有另外的惊喜哦....."
        outMsg.setContent("欢迎关注大脸猫！精选京城最优质美容养生店面，平台担保交易，价格优惠，消费透明，全程无推销。点击下方的“预约”，开始您的奇妙之旅吧^_^");
        if("subscribe".equals(inFollowEvent.getEvent())){
            ApiResult userInfo = UserApi.getUserInfo(inFollowEvent.getFromUserName());
            if(StringUtils.isBlank(userInfo.getStr("errormessage"))){
                Users user = new Users();
                user.set(Users.sex,userInfo.getInt("sex"));
                user.set(Users.openid,userInfo.getStr("openid"));
                user.set(Users.nickname,userInfo.getStr("nickname"));
                user.set(Users.city,userInfo.getStr("city"));
                user.set(Users.province,userInfo.getStr("province"));
                user.set(Users.country,userInfo.getStr("country"));
                user.set(Users.headimgurl,userInfo.getStr("headimgurl"));
                user.set(Users.subscribe_time,userInfo.getInt("subscribe_time")+"");
                user.set(Users.unionid,userInfo.getStr("unionid"));
                try{
                    user.save();
                }catch (Exception e){
                    logger.error(e.getMessage(),e);
                }
                System.out.println(user.toJson());
            }
        }
        System.out.println("返回消息");
        // 如果为取消关注事件，将无法接收到传回的信息
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理扫描带参数二维码事件
     */
    protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
//        OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
//        outMsg.setContent("processInQrCodeEvent() 方法测试成功");
//        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理上报地理位置事件
     */
    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
//        OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
//        outMsg.setContent("processInLocationEvent() 方法测试成功");
//        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
//        renderOutTextMsg("processInMenuEvent() 方法测试成功");
    }

    /**
     * 实现父类抽方法，处理接收语音识别结果
     */
    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
        renderOutTextMsg("语音识别结果： " + inSpeechRecognitionResults.getRecognition());
    }
}






